package com.leet.bfs;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class DAG {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] in = new int[numCourses];
        List<List<Integer>> segment = new ArrayList<>();
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0 ;i < numCourses;i++){
            segment.add(new ArrayList<>());
        }
        for(int[] arr: prerequisites){
            in[arr[0]]++;
            segment.get(arr[1]).add(arr[0]);
        }
        //刚开始，加入入度为0的
        for(int i = 0;i < numCourses;i++){
            if(in[i] == 0){
                q.offer(i);
            }
        }
        while (!q.isEmpty()){
            int head = q.poll();
            numCourses--;
            for(int index:segment.get(head)){
                in[index]--;
                if(in[index]==0) q.add(index);
            }
        }
        return numCourses == 0;
  }
}
